// 匹配第一个?符号之前的内容
function getContentRegexp(str) {
  const regexBeforeQuestionMark = /^(.*?)(\?|$)/;
  const match = str.match(regexBeforeQuestionMark);
  return match ? match[1] : '';
}

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  // 确保消息来自本扩展
  if (sender.id !== chrome.runtime.id) {
    return;
  }
  if (message.action == 'dl_background') {
    const { urls, fileName } = message;
    urls.forEach((item, index) => {
      let [, ext] = getContentRegexp(item.split('/').pop()).split('.');
      alert(`dl_background ${item} ${fileName}-${index}.${ext}`);
      chrome.downloads.download({
        url: item,
        saveAs: false,
        filename: `${fileName}-${index}.${ext}`,
        conflictAction: 'uniquify',
      });
    });
    return;
  }
  // 关闭当前标签页
  else if (message.action === 'closeTabAfterDownload') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs && tabs.length > 0) {
        chrome.tabs.remove(tabs[0].id);
      }
    });
    return;
  }
  chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
    chrome.tabs.sendMessage(tabs[0].id, message);
  });
});
